package com.app;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GiftAppServlet
 */
public class GiftAppServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private GiftApp application;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GiftAppServlet() {
        super();
        application = new GiftApp();
        application.init();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter pw = response.getWriter();
		String gifter = (String)request.getParameter("Gifter");
		String slno = (String)request.getParameter("Slno");;
		application.setCheckForName(gifter);
		
		if (application.isNameExists() && application.checkForSerialNumber(slno) && !application.isAlreadyRegistered(gifter)) {
			String randomName = application.getRandomNameFor(gifter);
			Integer cubicleNo = application.getCubicleNumberFor(randomName);
			application.markUserAsRegistered(gifter, randomName);
			application.updateNameList(randomName);	
			pw.println("<br>You may gift a present to <h2>"+ randomName +"</h2>");
			pw.println("<br>Your Giftee's Cubicle Number is : <h4>"+ cubicleNo +"</h4>");
			if (gifter.compareTo(randomName) == 0)
				pw.println("<br>Tough Luck!!! You have got yourself to Gift to.. Really Sorry!!!");
//			pw.println("<br>Please note the name as it wont be able to retrieve again!!!" );
		}
		else if(application.isNameExists() && application.checkForSerialNumber(slno) && application.isAlreadyRegistered(gifter)){
			String randomName = application.getAdmirer(gifter);
			Integer cubicleNo = application.getCubicleNumberFor(randomName);
			pw.println("<br>You may gift a present to <h2>"+ randomName +"</h2>");
			pw.println("<br>Your Giftee's Cubicle Number is : <h4>"+ cubicleNo +"</h4>");
		}
		else {
			pw.println("<h4> Either the name is not listed [or] you have entered a wrong Serial Number!!!! Sorry... </h4>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
